#!/bin/sh

version="$1"

[ -x /usr/sbin/update-initramfs ] || exit 0

# passing the kernel version is required
if [ -z "$version" ]; then
	echo >&2 "W: initramfs-tools: ${DPKG_MAINTSCRIPT_PACKAGE:-kernel package} did not pass a version number"
	exit 0
fi

# avoid running multiple times
if [ -n "$DEB_MAINT_PARAMS" ]; then
	eval set -- "$DEB_MAINT_PARAMS"
	if [ -z "$1" ] || [ "$1" != "upgrade" ]; then
		exit 0
	fi
fi

STATEDIR=/var/lib/initramfs-tools

version_list="$(ls -1 "$STATEDIR" | linux-version sort --reverse)"

for v in $version_list; do
	if ! linux-version compare $v eq $version; then
		# try to delete delete old initrd images via update-initramfs
		INITRAMFS_TOOLS_KERNEL_HOOK=y update-initramfs -d -k $v 2>/dev/null
		# delete unused state files
		find $STATEDIR -type f ! -name "$version" -printf "Removing obsolete file %f\n" -delete
		# delete unused initrd images
		find /boot -name "initrd.img*" -o -name "uInitrd-*" ! -name "*$version" -printf "Removing obsolete file %f\n" -delete
	fi
done

exit 0
